import axios from 'axios'
import { getToken } from '@/utils/auth'
import { TokenKey } from '@/emnus/auth'
import type { AxiosInstance } from 'axios'
import type { IRequestInterceptors, IHttpRequestConfig } from './type'
import store from '../../store'
import qs from 'qs'
import api from '@/api'
// import { ElLoading } from 'element-plus'
// import { ILoadingInstance } from 'element-plus/lib/el-loading/src/loading.type'

const DEFAULT_LOADING = true
class httpRequest {
  instance: AxiosInstance
  interceptors?: IRequestInterceptors
  showLoading: boolean
  // loading?: ILoadingInstance
  constructor(config: IHttpRequestConfig) {
    // 创建axios实例
    this.instance = axios.create(config)
    // 保存基本信息
    this.interceptors = config.interceptors
    this.showLoading = config.showLoading ?? DEFAULT_LOADING

    // 拦截器
    // 1.config传入的不同实例对应的拦截器
    this.instance.interceptors.request.use(
      this.interceptors?.requestInterceptor,
      this.interceptors?.requestInterceptorCatch
    )
    this.instance.interceptors.response.use(
      this.interceptors?.responseInterceptor,
      this.interceptors?.responseInterceptorCatch
    )

    // 2.全局拦截器
    this.instance.interceptors.request.use(
      (config) => {
        // 携带token
        // const token = getToken() //store或localStorage
        // if (token) {
        //   config.headers = {
        //     ...config.headers,
        //     [TokenKey]: token
        //   }
        // }
        // 添加全局loading
        // if (this.showLoading) {
        //   this.loading = ElLoading.service({
        //     lock: true,
        //     background: 'rgba(0,0,0,0.5)'
        //   })
        // }
        if (!config.url?.includes('sm2')) {
          // 参数序列化
          config.paramsSerializer = function (params) {
            return qs.stringify(params, { arrayFormat: 'repeat' })
          }
        } else {
          config.data = qs.stringify(config.data)
          config.headers = {
            ['Content-Type']: 'application/x-www-form-urlencoded;charset=UTF-8'
          }
        }
        // 携带token
        const token = getToken() //store或localStorage
        if (token) {
          config.headers = {
            ...config.headers,
            'Bdsoft-Token': token
          }
        }
        return config
      },
      (err) => {
        return err
      }
    )
    this.instance.interceptors.response.use(
      (res) => {
        // this.loading?.close()
        // const data = res.data
        // if (data.code !== 200) {
        //   console.log('请求失败:code不等于200')
        //   return
        // }
        //直接返回data
        return res.data
      },
      (err) => {
        // this.loading?.close()
        // 响应失败拦截,判断HttpErrorCode显示不同错误信息
        // switch(err.response.status)
        return err
      }
    )
  }
  request<T>(config: IHttpRequestConfig<T>): Promise<T> {
    return new Promise((resolve, reject) => {
      // 是否添加loading
      if (config.showLoading === false) {
        this.showLoading = false
      }
      if (store && !config.params.startDate && !config.params.endDate) {
        const { startDate, endDate } = store.state.globalDate
        config.params = { ...config.params, startDate, endDate }
      }
      this.instance
        .request<any, T>(config)
        .then((res) => {
          if (config.interceptors?.responseInterceptor) {
            res = config.interceptors.responseInterceptor(res)
          }
          this.showLoading = DEFAULT_LOADING
          resolve(res)
        })
        .catch((err) => {
          this.showLoading = DEFAULT_LOADING
          reject(err)
          return err
        })
    })
  }

  get<T = any>(config: IHttpRequestConfig<T>): Promise<T> {
    const url: string = config.url as string
    if (isOnline) {
      config.url = onlineUrl.url
      if (config.params) {
        config.params.function = onlineAPI[url]
      } else {
        config.params = {
          function: onlineAPI[url]
        }
      }
    } else {
      config.url = api[url]
    }
    const method = isOnline ? 'POST' : 'GET'
    return this.request<T>({ ...config, method: method })
  }

  post<T = any>(config: IHttpRequestConfig<T>): Promise<T> {
    // const url: string = config.url as string
    // if (isOnline) {
    //   config.url = onlineUrl.url
    //   if (config.params) {
    //     config.params.function = onlineAPI[url]
    //   } else {
    //     config.params = {
    //       function: onlineAPI[url]
    //     }
    //   }
    // } else {
    //   config.url = api[url]
    // }
    const method = 'POST'
    return this.request<T>({ ...config, method: method })
  }
}

export default httpRequest
